import java.util.List;
import java.util.concurrent.TimeUnit;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

import com.auto.entity.Task;
import com.auto.pojo.Command;
import com.google.common.collect.Lists;

public class Main {
	private WebDriver driver;
	private String baseUrl;

	public void init(String baseUrl, Long timeout) throws Exception {
		driver = new FirefoxDriver();
		this.baseUrl = baseUrl;
		driver.manage().timeouts().implicitlyWait(timeout, TimeUnit.SECONDS);
		driver.get(baseUrl);
	}

	public void execute(Command command) {
		WebElement we = driver.findElement(getTarget(command));
		if (command.getName().equals("clickAndWait")) {
			we.click();
		} else if (command.getName().equals("type")) {
			we.clear();
			we.sendKeys(command.getValue());
		}
	}

	public static By getTarget(Command command) {
		if (command.getTargetMethod().equals("link")) {
			return By.linkText(command.getTargetValue());
		} else if (command.getTargetMethod().equals("id")) {
			return By.id(command.getTargetValue());
		}
		return null;
	}

	public List<Command> getCommand(Task task) {
		List<Command> cmds = Lists.newArrayList();
		Document doc = Jsoup.parse(task.getContent());
		Elements trs = doc.select("tbody").select("tr");
		for (int i = 0; i < trs.size(); ++i) {
			Elements tds = trs.get(i).select("td");
			Command cmd = new Command();
			cmd.setName(tds.get(0).text());
			cmd.setName(tds.get(0).text());
			String[] target = tds.get(1).text().split("=");
			cmd.setTargetMethod(target[0]);
			if (target.length > 1) {
				cmd.setTargetMethod(target[1]);
			}
			cmd.setValue(tds.get(2).text());
		}
		return cmds;

	}

	public void exit() {
		driver.quit();
	}

	public static void main(String[] args) throws Exception {
		Main m = new Main();
		m.init("http://www.iteye.com/", 30L);
		Command command = new Command();
		command.setTargetMethod("linkText");
		command.setTargetValue("登录");
		m.execute(command);
		m.exit();
	}
}
